#!/usr/bin/python
#-*- coding: UTF-8 -*-
import os
import json
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from operator import itemgetter, attrgetter
from django.contrib.auth.models import User as Django_User
from django.contrib.auth.models import Permission as Django_Permission

from cloudengine.logger  import logger
from cloudengine.const   import *
from cloudengine.utility import *
from cloudengine.models  import *
from cloudengine.sshapi  import *
from cloudengine.ldapapi import *
from cloudengine.virtapi import *
from cloudengine.service.license import *


########################################################
#
# Account Related Implementation                                ##账户相关执行
#
########################################################
def __getUsers():          #获取用户
    rusers = []

    try:
        (ls, lp, lbdn, lau, lap) = getLdapServer()
        with_ldap = True
    except Exception, e2:
        with_ldap = False

    #如果设置了LDAP参数，则添加到LDAP服务器，否则添加到本地数据库
    if with_ldap:
        for t in listLdapUsers(ls, lp, lbdn, lau, lap):
            tinfo = getLdapUserInfo(ls, lp, lbdn, lau, lap, t)
            ruser = {}
            ruser['username'] = tinfo['cn']
            ruser['fullname'] = tinfo['displayName']
            ruser['mail']     = ''
            ruser['domain']   = 'true'
            rusers.append(ruser)    #将字典ruser里的内容添加到rusers列表里去
    for t in User.objects.all():
        ruser = {}
        ruser['username'] = t.tusername
        ruser['fullname'] = t.tfullname
        ruser['mail']     = t.tmail
        ruser['domain']   = 'false'  #域名
        rusers.append(ruser)
    return rusers          #调用__getUsers()函数返回rusers列表


def list_users(request):
    logger.info("Entering list_users...")

    try:
        rusers = __getUsers()

        total = len(rusers)                 #记录数
        lnum  = checkLicense()
        if lnum < 16:                       #试用版本最多返回16条记录
           lnum = 16
        if total > lnum:
           total = lnum
        rusers = rusers[0:total]

        logger.info(rusers)
        return HttpResponse(json.dumps({'code':'True', 'message':rusers}))
    except Exception, e:
        logger.error(str(e))
        return HttpResponse(json.dumps({'code':'False', 'message':str(e)}))


def list_grid_users(request):
    logger.info("Entering list_grid_users...")
    offset = int(request.GET.get('offset', '1'))
    limit  = int(request.GET.get('limit', '10'))
    sort   = request.GET.get('sort',  '')
    order  = request.GET.get('order', '')
    logger.info("offset: %d, limit: %d, sort: %s, order: %s" % (offset, limit, sort, order))

    try:
        rusers = __getUsers()

        total = len(rusers)                 #记录数
        lnum  = checkLicense()
        if lnum < 16:                       #试用版本最多返回16条记录
           lnum = 16
        if total > lnum:
           total = lnum
        rusers = rusers[0:total]

        if sort:
            if order == "asc":
                rusers.sort(key=itemgetter(sort), reverse=True)
            else:
                rusers.sort(key=itemgetter(sort), reverse=False)

        logger.info(rusers)
        return HttpResponse(json.dumps({'total':total, 'rows':rusers[offset:(limit+offset)]}))
    except Exception, e:
        logger.error(str(e))
        return HttpResponse(json.dumps({'total':0, 'rows':[]}))


def __addUser(username, fullname, password, mail):
    #这里要将用户添加为Ldap用户，属于user组
    try:
        (ls, lp, lbdn, lau, lap) = getLdapServer()
        with_ldap = True
    except Exception, e:
        with_ldap = False

    #如果设置了LDAP参数，则添加到LDAP服务器，否则添加到本地数据库
    if with_ldap:
        logger.info("Adding to Ldap Server: %s" % username)
        addLdapUser(ls, lp, lbdn, lau, lap, username, username, fullname, fullname, mail, password)
        addToLdapGroup(ls, lp, lbdn, lau, lap, str(username), 'allusers')
        logger.info("Added to Ldap Server.")
        #这里要将用户添加到虚拟化平台
        try:
            (dip, dusername, dpassword, rpassword, sshport) = getDeskEngine()
            #查找和LDAP匹配的域
            for x in getDomainIds(dip, dusername, dpassword):
                dname = getDomainName(dip, dusername, dpassword, x)
                #LDAP格式：dc=test,dc=com，域名格式：authz-test.com
                if '.'.join(x[3:] for x in lbdn.split(',')) in dname:
                    logger.info("Adding to Desk Engine: %s(%s)" % (username, dname)) 
                    addUser(dip, dusername, dpassword, username, dname)
                    logger.info("Added to Desk Engine.")
        except Exception, e:
            logger.warning("Failed while adding to Desk Engine: %s" % str(e))
            #我们应该允许系统脱离云桌面而存在（例如只使用类教学活动相关功能）(aoqingy)
    else:
        logger.info("Adding to Local Database: %s" % username)
        user = User(tusername=username, tfullname=fullname, tpassword=password, tmail=mail)
        user.save()
        duser = Django_User.objects.create_user(username, username, password)
        dpermission = Django_Permission.objects.get(codename="localuser")
        duser.user_permissions.add(dpermission)
        logger.info("Added to Local Database.")

    return


def add_user(request):    #添加用户
    logger.info("Entering add_user...")
    username = request.POST.get('username')
    fullname = request.POST.get('fullname')
    password = request.POST.get('password')
    mail     = request.POST.get('mail')
    logger.info("username: %s, fullname: %s, mail: %s" % (username, fullname, mail))

    try:
        __addUser(username, fullname.encode('utf8'), password, mail)
        logger.info('Done!')
        return HttpResponse(json.dumps({'code':'True', 'message':'Done!'}))
    except Exception, e:
        logger.error(str(e))
        return HttpResponse(json.dumps({'code':'False', 'message':str(e)}))


def import_users(request):   #导入用户
    logger.info("Entering import_users...")

    try:
        #将上传文件保存到临时目录下
        if len(request.FILES.items()) != 1:
            raise Exception("Only one file allowed!")

        name, srcf = request.FILES.items()[0]
        logger.info('Uploading file %s...' % srcf.name)

        fpath = "/tmp/%s" % srcf.name
        f = open(fpath, 'w')
        for chunk in srcf.chunks():
            f.writelines(chunk)
        f.close()

        #根据文件内容添加用户
        with open(fpath, 'r') as f:
            for line in f.readlines():
                try:
                    line = line.strip()
                    username, fullname, password, mail = line.split(',')
                    __addUser(username, fullname.decode('gbk').encode('utf8'), password, mail)
                except Exception, e2:
                    logger.warning("%s: %s" % (line, str(e2)))

        #删除临时文件
        os.remove(fpath)

        logger.info('Done!')
        return HttpResponse(json.dumps({'code':'True', 'message':'Done!'}))
    except Exception, e:
        logger.error(str(e))
        return HttpResponse(json.dumps({'code':'False', 'message':str(e)}))


def __removeUser(username):
    try:
        (ls, lp, lbdn, lau, lap) = getLdapServer()
        with_ldap = True
    except Exception, e:
        with_ldap = False

    if with_ldap:
        try:
            (dip, dusername, dpassword, rpassword, sshport) = getDeskEngine()
            for x in getUserIds(dip, dusername, dpassword):
                if username == getUserName(dip, dusername, dpassword, x):
                    logger.info("Removing from Desk Engine: %s" % username)
                    removeUser(dip, dusername, dpassword, x)
                    logger.info("Removed from Desk Engine.")
        except Exception, e:
            logger.warning(str(e))

        logger.info("Removing from Ldap Server: %s" % username)
        deleteLdapUser(ls, lp, lbdn, lau, lap, username)       #从LDAP数据库中删除
        logger.info("Removed from Ldap Server.")
    else:
        logger.info("Removing from Local Database: %s" % username)
        user = User.objects.get(tusername=username)
        user.delete()
        duser = Django_User.objects.get(username=username)
        duser.delete()
        logger.info("Removed from Local Database.")


def remove_users(request):   #删除用户
    logger.info("Entering remove_users...")
    usernames = request.POST.get('usernames')
    logger.info("usernames: %s" % usernames)

    try:
        for username in usernames.split(','):
            try:
                __removeUser(username)
            except Exception, e2:
                logger.warning(str(e2))

        logger.info('Done!')
        return HttpResponse(json.dumps({'code':'True', 'message':'Done!'}))
    except Exception, e:
        logger.error(str(e))
        return HttpResponse(json.dumps({'code':'False', 'message':str(e)}))


def __changeUserPassword(username, password):  #更改用户密码
    try:
        (ls, lp, lbdn, lau, lap) = getLdapServer()
        with_ldap = True
    except Exception, e:
        with_ldap = False

    if with_ldap:
        logger.info("Changing password for user from Ldap Server...")
        setLdapUserPassword(ls, lp, lbdn, lau, lap, username, password)
        logger.info("Changed.")
    else:
        logger.info("Changing password for user from Local Database...")
        user = User.objects.get(tusername=username)
        user.password = password
        user.save()
        #duser = Django_User.objects.create_user(username, username, password)
        #dpermission = Django_Permission.objects.get(codename="localuser")
        #duser.user_permissions.add(dpermission)
        logger.info("Changed.")

    return


def change_user_password(request):            #更改用户密码
    logger.info("Entering change_user_password...")
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    logger.info("username: %s" % username)

    try:
        __changeUserPassword(username, password)
        logger.info('Done!')
        return HttpResponse(json.dumps({'code':'True', 'message':'Done!'}))
    except Exception, e:
        logger.error(str(e))
        return HttpResponse(json.dumps({'code':'False', 'message':str(e)}))
